package com.iiiu.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iiiu.payment.domain.entity.PaymentMethod;
import com.iiiu.payment.mapper.PaymentMethodMapper;
import com.iiiu.payment.service.PaymentMethodService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 支付方式服务实现类
 */
@Service
public class PaymentMethodServiceImpl extends ServiceImpl<PaymentMethodMapper, PaymentMethod> implements PaymentMethodService {

    @Override
    public List<PaymentMethod> getByUserId(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public PaymentMethod getByUserIdAndName(Long userId, String name) {
        return baseMapper.selectByUserIdAndMethodName(userId, name);
    }

    @Override
    public PaymentMethod createPaymentMethod(PaymentMethod paymentMethod) {
        // 检查名称是否已存在
        if (existsByUserIdAndName(paymentMethod.getUserId(), paymentMethod.getMethodName())) {
            throw new RuntimeException("支付方式名称已存在");
        }

        // 设置排序顺序
        if (paymentMethod.getSortOrder() == null) {
            // 获取当前用户的最大排序值
            LambdaQueryWrapper<PaymentMethod> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PaymentMethod::getUserId, paymentMethod.getUserId())
                       .eq(PaymentMethod::getIsDelete, 0)
                       .orderByDesc(PaymentMethod::getSortOrder)
                       .last("LIMIT 1");
            
            PaymentMethod lastMethod = getOne(queryWrapper);
            int nextOrder = lastMethod != null ? lastMethod.getSortOrder() + 1 : 1;
            paymentMethod.setSortOrder(nextOrder);
        }

        paymentMethod.setIsDelete(0);
        save(paymentMethod);
        return paymentMethod;
    }

    @Override
    public PaymentMethod updatePaymentMethod(PaymentMethod paymentMethod) {
        PaymentMethod existingMethod = getById(paymentMethod.getId());
        if (existingMethod == null) {
            throw new RuntimeException("支付方式不存在");
        }

        // 检查是否属于当前用户
        if (!existingMethod.getUserId().equals(paymentMethod.getUserId())) {
            throw new RuntimeException("无权限修改此支付方式");
        }

        // 检查名称是否重复（排除自己）
        PaymentMethod duplicateMethod = getByUserIdAndName(paymentMethod.getUserId(), paymentMethod.getMethodName());
        if (duplicateMethod != null && !duplicateMethod.getId().equals(paymentMethod.getId())) {
            throw new RuntimeException("支付方式名称已存在");
        }

        // 更新字段
        if (StringUtils.hasText(paymentMethod.getMethodName())) {
            existingMethod.setMethodName(paymentMethod.getMethodName());
        }
        if (StringUtils.hasText(paymentMethod.getDescription())) {
            existingMethod.setDescription(paymentMethod.getDescription());
        }
        if (paymentMethod.getSortOrder() != null) {
            existingMethod.setSortOrder(paymentMethod.getSortOrder());
        }

        updateById(existingMethod);
        return existingMethod;
    }

    @Override
    public boolean deletePaymentMethod(Long id) {
        PaymentMethod paymentMethod = getById(id);
        if (paymentMethod == null) {
            return false;
        }
        // 软删除
        paymentMethod.setIsDelete(1);
        return updateById(paymentMethod);
    }

    @Override
    public boolean existsByUserIdAndName(Long userId, String name) {
        LambdaQueryWrapper<PaymentMethod> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentMethod::getUserId, userId)
                   .eq(PaymentMethod::getMethodName, name)
                   .eq(PaymentMethod::getIsDelete, 0);
        return count(queryWrapper) > 0;
    }

    @Override
    public boolean updateSortOrder(Long userId, List<Long> paymentMethodIds) {
        if (paymentMethodIds == null || paymentMethodIds.isEmpty()) {
            return false;
        }

        try {
            for (int i = 0; i < paymentMethodIds.size(); i++) {
                Long id = paymentMethodIds.get(i);
                PaymentMethod paymentMethod = getById(id);
                
                if (paymentMethod != null && paymentMethod.getUserId().equals(userId)) {
                    paymentMethod.setSortOrder(i + 1);
                    updateById(paymentMethod);
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}